package com.borya.dao.impl;

import com.alibaba.fastjson.JSONObject;
import com.borya.dao.SdkAppDao;
import com.borya.framework.annotation.Component;
import com.borya.framework.core.ServerSqlSession;
import com.borya.model.db.*;
import com.borya.util.AppConf;
import com.borya.util.Constant;
import org.apache.log4j.Logger;

import java.util.Optional;

@Component("sdkAppDaoImpl")
public class SdkAppDaoImpl extends BaseDAOImpl implements SdkAppDao {

    public Logger log = Logger.getLogger(getClass());

    @Override
    public User getSdkAppUser(String phone, Integer detailType) {
        StringBuilder sql = new StringBuilder(256);
        sql.append("SELECT dealer_id,userid,citycode,cityname,a.tmsi,");
        sql.append("user_name,flag,source_type,detail_type,last_time FROM ");
        sql.append("tb_user_client ");
        sql.append(" WHERE detail_type=? AND userid=? ");
        sql.append("AND flag=1 ORDER BY createtime DESC LIMIT 1");
        try (ServerSqlSession session = getSqlDataSource().session()) {
            return session.executeQuery(sql.toString(), rs -> {
                if (rs != null && rs.next()) {
                    User user = new User();
                    user.setDealerId(rs.getString("dealer_id"));
                    user.setUserId(rs.getString("userid"));
                    user.setCityCode(rs.getString("citycode"));
                    user.setCityName(rs.getString("cityname"));
                    user.setTmsi(rs.getLong("tmsi"));
                    user.setInviteCode(rs.getString("invite_code"));
                    user.setLeftFee(rs.getLong("left_fee"));
                    user.setUserName(rs.getString("user_name"));
                    user.setDealerId(rs.getString("dealer_id"));
                    user.setPhone(rs.getString("phone"));
                    user.setFlag(rs.getInt("flag"));
                    user.setSourceType(rs.getInt("source_type"));
                    user.setDetailType(rs.getInt("detail_type"));
                    user.setLastTime(rs.getLong("last_time"));
                    return user;
                }
                return null;
            }, detailType, phone);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public Merchant getMerchant(String content, int type) {
            StringBuilder sb = new StringBuilder(128);
            sb.append("SELECT dealer_id,company_name");
            sb.append(",flag,source_type,ytsk_status");
            sb.append(",isSignAgreement,status,merchant_attribute,attribute_status");
            sb.append(",super_dealer_id");
            sb.append(",merchant_id");
            sb.append(",user_type_id,business_licence,address,popchannel,head_popchannel,createtime,devMac");
            sb.append(",merchant_type,sign_time,sign_picture,bond,banner_ids,super_dealer_name");
            sb.append(",regist_time");
            sb.append(" FROM tb_merchant ");
            sb.append(" WHERE ");
            if (type == Constant.GetMemInfoTye.BYDEALERID)
                sb.append(" dealer_id=? limit 1");
            else if (type == Constant.GetMemInfoTye.BYMERCHANTID)
                sb.append(" merchant_id=? limit 1");
        try (ServerSqlSession session = getSqlDataSource().session();) {
            return session.executeQuery(sb.toString(), rs -> {
                if (rs != null && rs.next()) {
                    Merchant mem = new Merchant();
                    mem.setDealerId(rs.getString("dealer_id"));
                    mem.setCompanyName(rs.getString("company_name"));
                    mem.setFlag(rs.getInt("flag"));
                    mem.setSourceType(rs.getInt("source_type"));
                    mem.setYtskStatus(rs.getInt("ytsk_status"));
                    mem.setIsSignAgreement(rs.getInt("isSignAgreement"));
                    mem.setStatus(rs.getInt("status"));
                    mem.setMerchant_attribute(rs.getInt("merchant_attribute"));
                    mem.setAttribute_status(rs.getInt("attribute_status"));
                    mem.setSuperDealerId(rs.getString("super_dealer_id"));
                    mem.setMerchantId(rs.getString("merchant_id"));
                    mem.setUserTypeId(rs.getInt("user_type_id"));
                    mem.setBusinessLicence(rs.getString("business_licence"));
                    mem.setAddress(rs.getString("address"));
                    mem.setPopChannel(rs.getString("popchannel"));
                    mem.setHeadPopChannel(rs.getString("head_popchannel"));
                    mem.setCreateTime(rs.getLong("createtime"));
                    mem.setDevMac(rs.getString("devMac"));
                    mem.setMerchantType(rs.getInt("merchant_type"));
                    mem.setSignTime(rs.getLong("sign_time"));
                    mem.setSignPicture(rs.getString("sign_picture"));
                    mem.setBond(rs.getInt("bond"));
                    mem.setBannerIds(rs.getString("banner_ids"));
                    mem.setSuperDealerName(rs.getString("super_dealer_name"));
                    mem.setRegistTime(rs.getLong("regist_time"));
                    return mem;
                }
                return null;
            }, content);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public ShqpInfo getShqpInfo(String dealerId) {
        try (ServerSqlSession session = getSqlDataSource().session();) {
            StringBuilder sb = new StringBuilder(128);
            sb.append("select dealer_id,shpq_id,shqp_end_time,shqp_url,shqp_send_msg");
            sb.append(",modify_time,device_id,sign_url");
            sb.append(" from tb_merchant_shqp ");
            sb.append(" where dealer_id=? limit 1");
            return session.executeQuery(sb.toString(), rs -> {
                if (rs != null && rs.next()) {
                    ShqpInfo shqpInfo = new ShqpInfo();
                    shqpInfo.setDealerId(rs.getString("dealer_id"));
                    shqpInfo.setShpqId(rs.getString("shpq_id"));
                    shqpInfo.setShqpEndTime(rs.getInt("shqp_end_time"));
                    shqpInfo.setShqpUrl(rs.getString("shqp_url"));
                    shqpInfo.setShqpSendMsg(rs.getInt("shqp_send_msg"));
                    shqpInfo.setModifyTime(rs.getLong("modify_time"));
                    shqpInfo.setDeviceId(rs.getString("device_id"));
                    shqpInfo.setSignUrl(rs.getString("sign_url"));
                    return shqpInfo;
                }
                return null;
            }, dealerId);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return null;
        }
    }

    @Override
    public User getUser(String content, int type) {
        try (ServerSqlSession session = getSqlDataSource().session();) {
            StringBuilder sb = new StringBuilder(128);
            sb.append("select dealer_id,is_main,createtime,tmsi,osversion,appversion,ostype");
            sb.append(",phonetype,net,citycode,cityname,applicationID,invite_code,user_name");
            sb.append(",last_time,alipay_user_id,weixin_user_id,user_type_id");
            sb.append(",host_ip,longitude,latitude,phone,flag,source_type,merchant_id");
            sb.append(",userid,alipay_user_name,detail_type,password");
            sb.append(" FROM tb_user_client ");
            sb.append(" WHERE ");
            sb.append(" source_type=").append(Constant.SourceType.XINIU);
            sb.append(" and detail_type=").append(AppConf.detailType);
            sb.append(" and flag=").append(Constant.Flag.FLAG_NORMAL);
            sb.append(" and ");
            switch (type) {
                case Constant.GetUserType.TYPE_INVITECODE:
                    sb.append("invite_code=? limit 1");
                    break;
                case Constant.GetUserType.TYPE_USERID:
                    sb.append("userid=? limit 1");
                    break;
                case Constant.GetUserType.TYPE_PHONE:
                    sb.append("phone=? limit 1");
                    break;
                default:
                    return null;
            }
            return session.executeQuery(sb.toString(), rs -> {
                if (rs != null && rs.next()) {
                    User u = new User();
                    u.setDealerId(rs.getString("dealer_id"));
                    u.setIsMain(rs.getInt("is_main"));
                    u.setCreateTime(rs.getLong("createtime"));
                    u.setTmsi(rs.getLong("tmsi"));
                    u.setOsVersion(rs.getString("osversion"));
                    u.setAppVersion(rs.getString("appversion"));
                    u.setOsType(rs.getString("ostype"));
                    u.setPhoneType(rs.getString("phonetype"));
                    u.setNet(rs.getString("net"));
                    u.setCityCode(rs.getString("citycode"));
                    u.setCityName(rs.getString("cityname"));
                    u.setApplicationID(rs.getString("applicationID"));
                    u.setInviteCode(rs.getString("invite_code"));
                    u.setUserName(rs.getString("user_name"));
                    u.setLastTime(rs.getLong("last_time"));
                    u.setAlipayUserId(rs.getString("alipay_user_id"));
                    u.setWeixinUserId(rs.getString("weixin_user_id"));
                    u.setUserTypeId(rs.getInt("user_type_id"));
                    u.setHostIp(rs.getString("host_ip"));
                    u.setLongitude(rs.getString("longitude"));
                    u.setLatitude(rs.getString("latitude"));
                    u.setPhone(rs.getString("phone"));
                    u.setFlag(rs.getInt("flag"));
                    u.setSourceType(rs.getInt("source_type"));
                    u.setMerchantId(rs.getString("merchant_id"));
                    u.setUserId(rs.getString("userid"));
                    u.setAlipayUserName(rs.getString("alipay_user_name"));
                    u.setDetailType(rs.getInt("detail_type"));
                    u.setPassword(rs.getString("password"));
                    return u;
                }
                return null;
            }, content);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public JSONObject getLivingCheckFlagInfo() {
        try (ServerSqlSession session = getSqlDataSource().session();) {
            StringBuilder sb = new StringBuilder(128);
            sb.append("select app_id,living_check_flag from tb_sdk_app_conf where flag = 1 ");
            return session.executeQuery(sb.toString(), rs-> {
                if(rs != null){
                    JSONObject obj = new JSONObject();
                    while(rs.next()){
                        obj.put(rs.getString(1),rs.getString(2));
                    }
                    return obj;
                }
                return null;
            });
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return null;
            }
    }

    @Override
    public Optional<UserClientDetail> getUserClientDetailByUser(String userId) {

        try (ServerSqlSession session = getSqlDataSource().session();) {
            StringBuilder sb = new StringBuilder(128);
            sb.append("select living_status,identity_card,identity_card_name,identify_photo_hand");
            sb.append(" from tb_user_client_detail where userid = ?");
            return session.executeQuery(sb.toString(), rs-> {
                if(rs != null){
                    UserClientDetail userClientDetail = new UserClientDetail();
                    while(rs.next()){
                        userClientDetail.setLivingStatus(Integer.valueOf(rs.getString("living_status")));
                        userClientDetail.setIdentityCard(rs.getString("identity_card"));
                        userClientDetail.setIdentityCardName(rs.getString("identity_card_name"));
                        userClientDetail.setIdentifyPhotoHand(rs.getString("identify_photo_hand"));
                    }
                    return Optional.ofNullable(userClientDetail);
                }
                return Optional.empty();
            },userId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Optional.empty();
        }
    }


}
